<?php
namespace App\Http\Controllers\Api;

use App\Model\UserLevelSetTable;
use App\Model\UserTable;
use App\Repository\BaseService;
use App\Repository\Common\ConstTable;
use App\Repository\BaseController\ApiController;
use App\Repository\Sys\JsonRespose;
use App\Repository\Sys\Str;
use App\Repository\Sys\Sys;
use Symfony\Component\HttpFoundation\Session\Session;

class UserController extends ApiController
{
    //用户-详情
    /**
     * @api {get} /api/user/user-info 用户详情
     * @apiGroup Wap-User
     * @apiDescription  说明: 无
     *
     * @apiParam {Int} id 用户ID
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": 1,
     * "msg": "操作成功!",
     * "data": {
     * "id":"1", --用户ID
     * "phone":"13554239409", --手机号
     * "img":"", --用户头像
     * "nickname":"qinzhiyong", --昵称
     * "birthday":"1993-03-24", --生日
     * "pwd":"", --密码
     * "status":"", --1启用 2禁用 -1删除
     * "team_id":"1,2,3", --所属球队ID
     * "team_id_text":"1,2,3", --所属球队名称
     * "vip":"1", --vip等级
     * "vip_text":"1", --vip等级文字
     * "integral":"300", --会员积分
     * "reg_time":"0000-00-00 00:00:00", --注册时间
     * "team_captain_id":"1", --球对队长ID
     * "num_booking":"1", --订场次数
     * "num_cancel":"1", --取消次数
     * "age":"1", --年龄
     * "team_list:":[]
     * }
     * }
     */
    public function getUserInfo()
    {
        $id = \Request::get('id');

        if (!$id) {
            $id = Sys::getUid();
        }
        if (!$id) {
            return Sys::getUidFail();
        }
        return JsonRespose::done(UserTable::getUserInfo($id));
    }

    /**
     * @api {post} /api/user/user-save 用户保存
     * @apiGroup Wap-User
     * @apiDescription  说明: 无
     *
     * @apiParam {Int} id 用户ID
     * @apiParam {Int} nickname 昵称
     * @apiParam {Int} img 用户头像
     * @apiParam {Int} birthday 生日
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": 1,
     * "msg": "操作成功!",
     * "data": {
     *    "id": 3
     * }
     * }
     */
    public function postUserSave()
    {
        $uid = Sys::getUid();
        if (!$uid) {
            return Sys::getUidFail();
        }

        $id = $uid;
        $nickname = \Request::get('nickname');
        $img = \Request::get('img');
        $age = \Request::get('age');
        $birthday = \Request::get('birthday');

        $birthday = Str::getDayTime($birthday);
        return JsonRespose::done(UserTable::postUserSave($id, $img, $birthday, $nickname, $age));
    }


    /**
     * @api {post} /api/user/reg 用户注册
     * @apiGroup Wap-User
     * @apiDescription  说明: 无
     *
     * @apiParam {Int} phone 手机号
     * @apiParam {Int} pwd 密码
     * @apiParam {Int} code 验证码
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     * "code": 1,
     * "msg": "操作成功!",
     * "data": {
     * "token": "a6bcbed2e3ded5169d47b37833cec015cb9d10a6",
     * "uid": 3,
     * "nickname": 123,
     * "img": 456
     * }
     * }
     */
    public function postReg()
    {
        $phone = \Request::get('phone');
        $pwd = \Request::get('pwd');
        $code = \Request::get('code');


        $nickname = session('wechat_user')['original']['nickname']; //  授权后存入 session 测试ing
        $img = session('wechat_user')['avatar'];

        $open_id = session('wechat_user')['original']['openid'];

        $user = UserTable::ORM()->where('phone', $phone)->first();
        if ($user) {
            return JsonRespose::fail('该手机号已注册');
        }
        $res = BaseService::useCode($phone, $code);
        if ($res['code'] != 1) {
            return JsonRespose::done($res);
        }

        $insert_data = [
            'nickname' => $nickname,
            'pwd' => md5($pwd),
            'status' => 1,
            'phone' => $phone,
            'img' => $img,
            'reg_time' => time(),
            'open_id' => $open_id,
            'birthday' => time()
        ];


        $uid = UserTable::ORM()->insertGetId($insert_data);
        session()->regenerate();
        session(['uid' => $uid]);
        UserLevelSetTable::updateLevel($uid, 0);  //更新会员等级与积分
        return JsonRespose::success(['token' => session()->getId(), 'uid' => $uid, 'nickname' => $nickname, 'img' => Str::getImg($img)]);
    }

    /**
     * @api {post} /api/user/login 登录
     * @apiGroup Wap-User
     * @apiDescription  说明: 无
     *
     * @apiParam {Int} phone 手机号
     * @apiParam {Int} pwd 密码
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     * "code": 1,
     * "msg": "登录成功",
     * "data": {
     * "uid": "3",
     * "token": "d4cd74684fd3c48847a1ae9ccf73a4109924d923"
     * }
     * }
     */
    public function postLogin()
    {
        $phone = \Request::get('phone');
        $pwd = trim(\Request::get('pwd'));
        $user = UserTable::ORM()->where('phone', $phone)->first();
        if (!$user) {
            return JsonRespose::fail('用户不存在');
        } 
        // 在同一个手机登陆其他账号  需要此代码， 配合退出的清空操作
        if (!$user->open_id) {
            UserTable::ORM()->where('phone', $phone)->update(['open_id'=>session('wechat_user')['original']['openid']]);
        }

        if ($user->status != 1) {
            return JsonRespose::fail('用户已禁用');
        }
        if ($user->pwd != md5($pwd)) {
            return JsonRespose::fail('密码错误');
        }
        session()->regenerate();
        session(['uid' => $user->id]);
        return JsonRespose::success(['uid' => $user->id, 'token' => session()->getId()], '登录成功');
    }


    /**
     * @api {post} /api/user/rest-pwd 重置密码
     * @apiGroup Wap-User
     * @apiDescription  说明: 无
     *
     * @apiParam {Int} phone 手机号
     * @apiParam {Int} pwd 新密码
     * @apiParam {Int} code 验证码
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     * "code": 1,
     * "msg": "操作成功!",
     * "data": {
     * "token": "b691b05d45c6af08ba988f722aad6bab47c56e91",
     * "uid": 1,
     * "nickname": "123",
     * "img": "456"
     * }
     * }
     */
    public function postRestPwd()
    {
        $phone = \Request::get('phone');
        $pwd = \Request::get('pwd');
        $code = \Request::get('code');


        $user = UserTable::ORM()->where('phone', $phone)->first();
        if (!$user) {
            return JsonRespose::fail('用户不存在');
        }
        $res = BaseService::useCode($phone, $code);
        if ($res['code'] != 1) {
            return JsonRespose::done($res);
        }

        $uid = UserTable::ORM()->where('phone', $phone)->update([
            'pwd' => md5($pwd),
        ]);
        session()->regenerate();
        session(['uid' => $uid]);
        return JsonRespose::success(['token' => session()->getId(), 'uid' => $uid, 'nickname' => $user->nickname, 'img' => Str::getImg($user->img)]);
    }

    /**
     * @api {get} /api/user/integral-list 积分列表
     * @apiGroup Wap-User
     * @apiDescription  说明: 无
     *
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     * "code": 1,
     * "msg": "操作成功!",
     * "data": {
     * "count": "6",
     * "integral": "300",
     * "list": [
     * {
     * "integral": 300,
     * "dateline": "2018-02-13 14:06",
     * "desc": "预定场地"
     * },
     * {
     * "integral": 300,
     * "dateline": "2018-02-13 14:06",
     * "desc": "预定场地"
     * },
     * {
     * "integral": 300,
     * "dateline": "2018-02-13 14:04",
     * "desc": "预定场地"
     * },
     * {
     * "integral": 300,
     * "dateline": "2018-02-13 14:04",
     * "desc": "预定场地"
     * },
     * {
     * "integral": 300,
     * "dateline": "2018-02-13 14:03",
     * "desc": "预定场地"
     * },
     * {
     * "integral": 1,
     * "dateline": "1970-01-01 08:00",
     * "desc": "应战"
     * }
     * ],
     * "page": 1
     * }
     * }
     */
    public function getIntegralList()
    {

        $page = \Request::get('page', 1);
        $limit = \Request::get('page_num', 10);

        $uid = Sys::getUid();
        if (!$uid) {
            return Sys::getUidFail();
        }

        return JsonRespose::done(UserTable::integralList($uid, $page, $limit));
    }


    /**
     * @api {get} /api/user/user-coupon 用户卡券列表
     * @apiGroup Wap-User
     * @apiDescription  说明: 无
     *
     * @apiParam {Int} page --
     * @apiParam {Int} page_num --
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     * "code": 1,
     * "msg": "操作成功!",
     * "data": {
     * "count": "1",
     * "list": [
     * {
     * "number": "0",
     * "phone": "13554239049",
     * "nickname": "qinzhiyong",
     * "start_time": "1970-01-01 08:00",
     * "end_time": "1970-01-01 08:00"
     * }
     * ],
     * "page": 1
     * }
     * }
     */
    public function getUserCoupon()
    {
        $page = \Request::get('page', 1);
        $limit = \Request::get('page_num', 100);

        $uid = Sys::getUid();
        if (!$uid) {
            return Sys::getUidFail();
        }


        $param = [];
        $where = "coupon_list.uid={$uid}";
        $count = \DB::select("select count(*) as c  from coupon_list WHERE {$where}", $param)[0]->c;
        $param['offset'] = ($page - 1) * $limit;
        $param['limit'] = $limit;
        $res = \DB::select("select coupon_list.*,`user`.phone,`user`.nickname from coupon_list LEFT  JOIN  `user` ON  `user`.id=coupon_list.uid WHERE {$where} ORDER BY coupon_list.id DESC limit :offset,:limit", $param);

        $list = [];
        foreach ($res as $v) {

            $v->start_time = date('Y-m-d H:i', $v->start_time);
            $v->end_time = date('Y-m-d H:i', $v->end_time);
            $v->dateline = date('Y-m-d H:i', $v->dateline);
            $list[] = $v;
        }
        $data = [
            'count' => $count,
            'list' => $list,
            'page' => $page,
        ];
        return JsonRespose::success($data);
    }

    /**
     * @api {post} /api/user/rest-phone 修改手机号
     * @apiGroup Wap-User
     * @apiDescription  说明: 无
     *
     * @apiParam {Int} phone 新手机号
     * @apiParam {Int} pwd 新密码
     * @apiParam {Int} code 验证码
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     * "code": 1,
     * "msg": "操作成功!",
     * "data": {
     * "token": "b691b05d45c6af08ba988f722aad6bab47c56e91",
     * "uid": 1,
     * "nickname": "123",
     * "img": "456"
     * }
     * }
     */
    public function postRestPhone()
    {

        $uid = Sys::getUid();
        if (!$uid) {
            return Sys::getUidFail();
        }

        $phone = \Request::get('phone');  //新手机号
        $pwd = \Request::get('pwd');
        $code = \Request::get('code');


        $user = UserTable::ORM()->where('phone', $phone)->first();
        if ($user) {
            return JsonRespose::fail('手机号已经存在了');
        }
        $user = UserTable::ORM()->where('id', $uid)->first();
        if (!$user) {
            return JsonRespose::fail('用户不存在');
        }
        if ($user->id != $uid) {
            return JsonRespose::fail('没有权限操作');
        }
        $res = BaseService::useCode($phone, $code);
        if ($res['code'] != 1) {
            return JsonRespose::done($res);
        }

        $uid = UserTable::ORM()->where('id', $uid)->update([
            'pwd' => md5($pwd),
            'phone' => $phone
        ]);
        session()->regenerate();
        session(['uid' => $uid]);
        return JsonRespose::success(['token' => session()->getId(), 'uid' => $uid, 'nickname' => $user->nickname, 'img' => Str::getImg($user->img)]);
    }
}
